<template>
  <div>
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch">
      <el-form-item label="流程名称" prop="flowName">
        <el-input v-model="queryParams.flowName" placeholder="请输入流程名称" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
        <!-- <el-button type="primary" size="small" icon="el-icon-plus" @click="handleAdd">发起流程</el-button> -->
      </el-form-item>
    </el-form>
    <el-table v-loading="loading" :data="declarationFilingList" @selection-change="handleSelectionChange">
      <el-table-column label="编号" prop="instanceId" align="center" />
      <el-table-column label="流程名称" prop="flowName" :show-overflow-tooltip="true" />
      <!-- <el-table-column label="学院" align="center" prop="orgId"  width="100" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span>{{collegeFormat(scope.row.orgId)}}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="发起人员" prop="createBy" :show-overflow-tooltip="true"  align="center" />
      <el-table-column label="发起时间" prop="createTime"  align="center">
      </el-table-column>
      <el-table-column label="提交时间" prop="startTime" align="center">
      </el-table-column>
      <el-table-column label="执行步骤" prop="nodeName" align="center" :show-overflow-tooltip="true" />
      <el-table-column label="操作" align="center" >
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-if="scope.row.flowStatusOpt=='uncommitted'">删除</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleDetail(scope.row)"
            v-if="scope.row.flowStatusOpt!=='uncommitted'">查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <ChooseUser @chooseUsers="getUser" ref="checkedUserCom"></ChooseUser>
    <DeclarationFilingDetail ref="previewCom" />
  </div>
</template>

<script>
  import {commitDeclarationFiling, listDeclarationFiling, getDeclarationFiling, delDeclarationFiling, addDeclarationFiling, updateDeclarationFiling, exportDeclarationFiling } from "@/api/labdata/declarationFiling";


  import { searchEmployee, getEmployeeInfo } from "@/api/labdata/employee";
  import { formatCurrentDate } from "@/utils/index";
  import { listOrgnization } from "@/api/labdata/orgnization";
  import { getUserProfile } from "@/api/system/user";
  import { treeselect } from "@/api/labdata/orgnization";
  import DeclarationFilingDetail from "@/views/labdata/declarationFiling/declarationFilingDetail.vue";
  import UploadCom from "@/views/labdata/commons/upload.vue";
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  import FlowChoose from '@/views/labdata/flowDefination/flow_choose.vue'
  import ChooseUser from "@/views/labdata/employee/user_choose_com.vue";
  import { getOrgByFunctionOpt, listSecondOrgLab } from "@/api/labdata/orgnization";
  import { listOrgThird, getOrgThird, delOrgThird, addOrgThird, updateOrgThird, exportOrgThird } from "@/api/labdata/orgThird";
  import { listInstrumentation, getInstrumentation, delInstrumentation, addInstrumentation, updateInstrumentation, exportInstrumentation } from "@/api/labbase/instrumentation";

  export default {
    name: "DeclarationFilingComponent",
    components: { UploadCom, Treeselect, FlowChoose, ChooseUser,DeclarationFilingDetail },
    data() {
      return {
        //二级机构
        secondOrgList: [],
        //二级机构下的实验室
        secondOrgLabList: [],
        // 实验室仪器列表
        instrumentationList: [],
        checkedUserList: [],
        choosedUserName: '',
        // 流程状态字典
        flowStatusOptOptions: [],
        showCopy: false,
        activeName: "first",
        // 部门树选项
        deptOptions: [],
        //用户对象
        user: {},
        // 表格树数据
        deptList: [],
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 实验室预约表格数据
        reservationList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 设置黑名单弹出层标题
        handTitle: "",
        // 设置黑名单是否显示弹出层
        handOpen: false,
        // 预约id
        globalReservationId: "",
        // 黑名单表单参数
        handForm: {
          blacklistId: null,
        },

        // 项目类型字典
        labProjectOptOptions: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          flowName: null,
          collegeOrgId: null
        },
        //附件集合
        fileList: [],
        // 黑名单附件集合
        handFileList: [],

        listDisabled: false,
        // 表单参数
        form: {
          //预约人员
          appointmentList: [],
          //参与人员
          participationList: []

        },
        // 组织机构申报备案列表
        declarationFilingList:[],
        // 表单校验
        rules: {
          flowName: [
            { required: true, message: "流程名称不能为空", trigger: "blur" }
          ]
        },
        // 黑名单表单检验
        handRules: {
          violationTime: [
            { required: true, message: "违规时间不能为空", trigger: "blur" }
          ]

        }
      };
    },
    watch: {
      checkedUserList: function (val) {
        this.choosedUserName = '';
        this.form.copyToUsers = '';
        val.forEach((item, index) => {
          if (index > 0) {
            this.choosedUserName += ",";
            this.form.copyToUsers += ",";
          }
          this.choosedUserName += item.nickName;
          this.form.copyToUsers += item.userId;
        })
      },
    },
    created() {
      this.getList();
    },

    methods: {
      getUser(e) {
        //console.log(JSON.stringify(e));
        this.checkedUserList = e;
      },
      selectUser() {
        if (this.checkedUserList && this.checkedUserList.length > 0) {
          this.$refs["checkedUserCom"].handleAdd(this.checkedUserList);
        } else {
          this.$refs["checkedUserCom"].handleAdd();
        }
      },
      setWorkflow(workflowId) {
        this.form.workflowId = workflowId;
        //console.log('workflow='+workflowId);
      },
      submitWorkflow() {
		if(!this.form.workflowId){
		    this.form.workflowId = this.$refs["workFlow"].getWorkflowId();
		}
        this.form.createBy = this.$store.state.user.name;
        commitReservation(this.form).then((response) => {
          this.msgSuccess("提交成功");
          this.open = false;
          this.getList();
        });
      },


      /** 查询部门下拉树结构 */
      getTreeselect() {
        treeselect().then(response => {
          this.deptOptions = response.data;
        });
      },
      //查询当前用户信息
      getUserInfo() {
        getUserProfile().then(response => {
          this.user = response.data;
        });
      },
      /** 查询部门列表 */
      getDeptList() {
        this.loading = true;
        this.queryParams = {}
        listOrgnization(this.queryParams).then(response => {
          this.deptList = response.rows;
        });
      },
      searchUser() {
        // console.log(this.form.projectOwnerId);
        if (!this.form.projectOwnerId) {
          this.form.projectLeader = null;
          this.form.ownerTitle = null;
          return;
        }
        searchEmployee(this.form.projectOwnerId).then(response => {
          let searchResult = response.data;
          if (searchResult && searchResult.length == 1) {
            this.form.projectLeader = searchResult[0].nickName;
            this.form.ownerTitle = searchResult[0].title
          } else {
            this.form.projectLeader = null;
            this.form.ownerTitle = null;
          }
          //强制刷新
          this.$forceUpdate();
        });
      },

      /** 查询实验室预约申请列表 */
      getList() {
        this.loading = true;
        listDeclarationFiling(this.queryParams).then(response => {
          this.declarationFilingList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 项目类型字典翻译
      labProjectOptFormat(row, column) {
        return this.selectDictLabel(this.labProjectOptOptions, row.labProjectOpt);
      },
      // 取消按钮
      cancel() {
        this.showCopy = false;
        this.open = false;
        this.reset();
        this.getList();
      },
      // 取消按钮
      handCancel() {
        this.handOpen = false;
        this.handReset();
      },
      // 表单重置
      handReset() {
        this.handForm = {
          blacklistId: null,
        };
        this.handFileList = [];
        this.resetForm("handForm");
      },
      // 表单重置
      reset() {
        this.form = {
          flowCreation: formatCurrentDate() + this.user.nickName + "创建",
          flowName: null,
        };
        this.fileList = [];
        this.checkedUserList = [];
        this.resetForm("form");
      },

      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.instanceId)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.form.createBy = this.$store.state.user.name;
        let employeeNo = this.$store.state.user.name;
        this.open = true;
        this.title = "添加实验室预约";
        getEmployeeInfo(employeeNo).then(response => {
          this.reset();
          this.form.appointmentList = response.data.appointmentList;
        })
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const instanceId = row.instanceId || this.ids
        getReservation(instanceId).then(response => {
          this.form = response.data;
          for (let key in this.form.appointmentList) {
            this.form.appointmentList[key].applicantOrgName = this.departmentOrgIdFormat(this.form.appointmentList[key].applicantOrgId)
          }
          for (let key in this.form.participationList) {
            this.form.participationList[key].applicantOrgName = this.departmentOrgIdFormat(this.form.participationList[key].applicantOrgId)
          }
          this.fileList = this.form.images;
          if (this.form.copyToUsers != null) {
            this.showCopy = true;
            getCheckedList({
              checkedUserIds: this.form.copyToUsers
            }).then(res => {
              this.checkedUserList = res.data;
            });
          }
          listSecondOrgLab(this.form.collegeOrgId).then(response => {
            this.secondOrgLabList = response.data;
            this.$forceUpdate();
          });
          getOrgThird(this.form.classRoomId).then(response => {
            this.form.totalSeats = response.data == undefined ? 0 : response.data.tableNums;
            this.$forceUpdate();
          });
          let params = {
            labId: this.form.classRoomId
          };
          listInstrumentation(params).then(response => {
            this.instrumentationList = response.rows;
            this.$forceUpdate();
          });
          this.open = true;
          this.searchUser();
          this.title = "修改实验室预约";
        });
      },

      /**查看 */
      handleDetail(row) {
        this.$refs['previewCom'].handleUpdate(row);
      },

      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.$refs["upload"].doSubmit();
          }
        });
      },

      /** 提交按钮 */
      submitData(fileList) {
        this.form.images = fileList;
        this.form.createBy = this.$store.state.user.name;
        if (this.form.instanceId != null) {
          updateReservation(this.form).then(response => {
            this.msgSuccess("修改成功");
            this.form = response.data;
            this.fileList = this.form.images;
            this.$forceUpdate();
            // this.open = false;
            // this.getList();
          });
        } else {
          addReservation(this.form).then(response => {
            this.msgSuccess("新增成功");
            this.form = response.data;
            this.fileList = this.form.images;
            // this.open = false;
            // this.getList();
          });
        }

      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const instanceIds = row.instanceId || this.ids;
        this.$confirm('是否确认删除实验室预约申请编号为"' + instanceIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return delReservation(instanceIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
      },
      // 流程状态字典翻译
      flowStatusOptFormat(row, column) {
        return this.selectDictLabel(this.flowStatusOptOptions, row.flowStatusOpt);
      },

      /** 提交按钮 */
      handSubmitForm() {
        this.$refs["handForm"].validate(valid => {
          if (valid) {
            this.$refs["handUpload"].doSubmit();
          }
        });
      },




      handleLabChange(item) {
        if (item) {
          this.form.classRoomId = null;
          this.form.instrumentDeviceId = null;
          this.form.totalSeats = null;
          listSecondOrgLab(item).then(response => {
            this.secondOrgLabList = response.data;
          });
        }
      },

      refreshChoose(item) {
        if (item) {
          this.form.instrumentDeviceId = null;
          this.form.totalSeats = null;
          getOrgThird(item).then(response => {
            this.form.totalSeats = response.data == undefined ? 0 : response.data.tableNums;
            this.$forceUpdate();
          });
          let params = {
            labId: item
          };
          listInstrumentation(params).then(response => {
            this.instrumentationList = response.rows;
          });
          this.$forceUpdate();
        }
      },
      change2() {
        this.$forceUpdate();
      },
      collegeFormat(value) {
        var datas = this.secondOrgList
        for (let key in datas) {
          if (datas[key].orgId == value) {
            return datas[key].orgName;
          }
        }
        return "";
      },

      // 实验室匹配
      classRoomIdFormat(value) {
        let datas = this.secondOrgLabList
        for (let key in datas) {
          if (datas[key].orgId == value) {
            return datas[key].orgName;
          }
        }
        return "";
      },
      // 所在部门字典翻译
      departmentOrgIdFormat(value) {
        var datas = this.deptList
        for (let key in datas) {
          if (datas[key].orgId == value) {
            return datas[key].orgName;
          }
        }
        return "";
      },
    }
  };
</script>
<style type="text/css" scoped lang="scss">
  .form_long {
    width: 596px;
  }

  .form_short {
    width: 200px;
  }

  /deep/ .el-button.active {
    text-decoration: underline;
    color: #0000ee;
  }

  /deep/ .el-button.dis_active {
    color: #999999
  }

  .select_view {
    display: flex;
    flex-direction: row;
    align-items: center;
  }

  .purchase_s_view {
    display: flex;
    flex-direction: row;
    //align-items: center;
  }

  .table_button {
    width: 100%;
    text-align: center;
    line-height: 20px;
    border-bottom: 1px solid #f6f5f5;
    color: #43bef8;
    cursor: pointer;
    border: 0;
  }

  /deep/ .el-dialog__body {
    padding: 0px 20px;
  }

  /deep/ .el-table__row .el-input--medium .el-input__inner {
    font-size: 10px;
    font-weight: 500;
    height: 30px;
    line-height: 30px;
  }
</style>
